package com.bitdf.txing.chat.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.TypeReference;
import com.bitdf.txing.chat.entity.ChatMessageEntity;
import com.bitdf.txing.chat.feign.ChatGroupFeignService;
import com.bitdf.txing.chat.feign.ChatSearchFeignService;
import com.bitdf.txing.chat.service.ChatMessageService;
import com.bitdf.txing.chat.service.ChatService;
import com.bitdf.txing.chat.service.FriendRelationService;
import com.bitdf.txing.chat.service.RedisService;
import com.bitdf.txing.chat.vo.GroupOutlineVo;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author lzw
 * @email 123@qq.com
 * @date 2022-11-23 22:43:49
 */
@RestController
@RequestMapping("${txing.request.path.chat}")
public class ChatMessageController {
    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private ChatService chatService;
    @Autowired
    FriendRelationService friendRelationService;
    @Autowired
    RedisService redisService;
    @Autowired
    ChatGroupFeignService txGroupFeignService;
    @Autowired
    ChatSearchFeignService txSearchFeignService;


    /**
     * 进入聊天室
     *
     * @return
     */
    @RequestMapping("/room/into")
    @SaCheckLogin
    public R roomInto() throws IOException {
        UserInfoVo userInfoVo = (UserInfoVo) StpUtil.getSession().get("user");

        //获取所有好友
        List<UserInfoVo> friendsList = friendRelationService.findFriends(userInfoVo.getId());
        //获取在线好友id
        List<Long> onlineFriendIds = chatService.getOnlineFriends(friendsList);
        //获取私聊记录
        Map<Long, List<ChatMessageEntity>> chatMessageHistory = chatMessageService.getLastestChatMessageHistory(userInfoVo.getId(), friendsList);
        //获取已读信息（私聊）
        Map<Long, Date> friendsLastReadTimeMap = redisService.getFriendsLastReadTime(userInfoVo.getId(), friendsList);
        /**
         * 获取群聊记录
         * 1、获取本用户所有群聊，获取各群聊的所有成员（详情）
         * 2、获取各群聊的聊天记录
         */
        //获取本用户的群聊以及各群聊的用户信息
        R r = txGroupFeignService.getGroupAndUserIdsByUserId(userInfoVo.getId());

        Map<String, List<Long>> groupUserIdsMap = (Map<String, List<Long>>) r.get("data");


        //获取群聊概要信息
        Set<String> longs = groupUserIdsMap.keySet();
        Set<Long> collect = longs.stream().map((item) -> {
                    return Long.parseLong(item);
                }
        ).collect(Collectors.toSet());
        R r1 = txSearchFeignService.getGroupSimpleByGroupIds(collect);
        List<GroupOutlineVo> groupOutlineList = r1.getData(new TypeReference<List<GroupOutlineVo>>() {
        });
        //获取各群聊的聊天记录
        Map<Long, List<ChatMessageEntity>> groupChatMessageHistory = chatMessageService.getLastestGroupChatMessageHistory(collect);

        Map<String, Object> hashMap = new HashMap<>();

        hashMap.put("friends", friendsList);
        hashMap.put("onlineFriendIds", onlineFriendIds);
        hashMap.put("messageHistory", chatMessageHistory);
        hashMap.put("lastReadTime", friendsLastReadTimeMap);
        hashMap.put("groupUserIdsMap", groupUserIdsMap);
        hashMap.put("groupOutlineList", groupOutlineList);
        hashMap.put("groupChatMessageHistory", groupChatMessageHistory);

        return R.ok().put("data", hashMap);
    }

    /**
     * 根据所传参数 获取私聊聊天记录
     *
     * @param fid
     * @param lastTimeStamp
     * @param count
     * @return
     */
    @GetMapping("/history/get")
    @SaCheckLogin
    public R getChatHistory(@RequestParam("fid") Long fid, @RequestParam("lastTimeStamp") Long lastTimeStamp,
                            @RequestParam("count") Integer count, @RequestParam("type") String type) {
        Long sid = ((UserInfoVo) StpUtil.getSession().get("user")).getId();
        List<ChatMessageEntity> res = chatMessageService.getChatMessageHistory(sid, fid, lastTimeStamp, count, type);
        return R.ok().put("data", res);
    }


    /**
     * 列表
     */
    @SaCheckLogin
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = chatMessageService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @SaCheckLogin
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ChatMessageEntity chatMessage = chatMessageService.getById(id);

        return R.ok().put("chatMessage", chatMessage);
    }

    /**
     * 保存
     */
    @SaCheckLogin
    @RequestMapping("/save")
    public R save(@RequestBody ChatMessageEntity chatMessage) {
        chatMessageService.save(chatMessage);

        return R.ok();
    }

    /**
     * 修改
     */
    @SaCheckLogin
    @RequestMapping("/update")
    public R update(@RequestBody ChatMessageEntity chatMessage) {
        chatMessageService.updateById(chatMessage);

        return R.ok();
    }

    /**
     * 删除
     */
    @SaCheckLogin
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        chatMessageService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
